/**
* 文件名：BinaryHttpResponseHandler.java
* 创建日期：
* Copyright (c)  西安西安乐食
* All rights reserved.
 
* 修改记录：
 * 1.修改时间：
 *   修改人：
 *   生成版本：
 *   修改内容：
*/
package com.uniknow.app.http;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.regex.Pattern;

import org.apache.http.Header;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.StatusLine;
import org.apache.http.client.HttpResponseException;
import org.apache.http.entity.BufferedHttpEntity;
import org.apache.http.util.EntityUtils;

import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Message;


/**
 * 类名称：ImageHttpResponseHandler   
 * 类描述：   针对图片下载所使用异步回调类
 * @创建者：zhangyao     
 * @创建时间：2014年7月3日
 * @变更记录：2014年7月3日上午9:09:43 by 记录变更人
 */
public class ImageHttpResponseHandler extends AsyncHttpResponseHandler {
    
	// Allow images by default
    private static String[] mAllowedContentTypes = new String[] {
        "image/jpeg",
        "image/png"
    };
	
    public static int MAX_WIDTH = 100;
    
	private File file;
	private File baseDirFile;
	
	private Bitmap bitmap;
	
	
   
    public ImageHttpResponseHandler(String filePath) {
        super();
		this.file = new File(filePath);
		this.baseDirFile = new File(this.file.getParent());
		init();
    }
    

    public ImageHttpResponseHandler(String rootFile, String fileName) {
        super();
		this.baseDirFile = new File(rootFile);
		this.file = new File(rootFile, fileName);
		init();
    }


	private void init()
	{
		// TODO Auto-generated method stub
		if (!this.baseDirFile.exists())
		{
			this.baseDirFile.mkdirs();
		}
	}

    
    /**
     * Creates a new ImageHttpResponseHandler, and overrides the default allowed
     * content types with passed String array (hopefully) of content types.
     */
    public ImageHttpResponseHandler(String rootFile, String fileName, String[] allowedContentTypes) {
        this(rootFile,fileName);
        mAllowedContentTypes = allowedContentTypes;
    }


    //
    // Callbacks to be overridden, typically anonymously
    //

    /**
     * Fired when a request returns successfully, override to handle in your own code
     * @param binaryData the body of the HTTP response from the server
     */
    public void onSuccess(Bitmap img) {}

    /**
     * Fired when a request returns successfully, override to handle in your own code
     * @param statusCode the status code of the response
     * @param binaryData the body of the HTTP response from the server
     */
    public void onSuccess(int statusCode,Bitmap img) {
        onSuccess(img);
    }

    /**
     * Fired when a request fails to complete, override to handle in your own code
     * @param error the underlying cause of the failure
     * @param binaryData the response body, if any
     * @deprecated
     */
    @Deprecated
    public void onFailure(Throwable error, byte[] binaryData) {
        // By default, call the deprecated onFailure(Throwable) for compatibility
        onFailure(error);
    }


    //
    // Pre-processing of messages (executes in background threadpool thread)
    //

    protected void sendSuccessMessage(int statusCode, byte[] responseBody) {
        sendMessage(obtainMessage(SUCCESS_MESSAGE, new Object[]{statusCode, responseBody}));
    }

    @Override
    protected void sendFailureMessage(Throwable e, byte[] responseBody) {
        sendMessage(obtainMessage(FAILURE_MESSAGE, new Object[]{e, responseBody}));
    }

   

    protected void handleSuccessMessage(int statusCode, Bitmap img) {
        onSuccess(statusCode, img);
    }

    protected void handleFailureMessage(Throwable e, byte[] responseBody) {
        onFailure(e, responseBody);
    }

    // Methods which emulate android's Handler and Message methods
    @Override
    protected void handleMessage(Message msg) {
        Object[] response;
        switch(msg.what) {
            case SUCCESS_MESSAGE:
                response = (Object[])msg.obj;
                handleSuccessMessage(((Integer) response[0]).intValue() ,  bitmap);
                break;          
            default:
                super.handleMessage(msg);
                break;
        }
    }

    // Interface to AsyncHttpRequest
    @Override
	protected
    void sendResponseMessage(HttpResponse response) {
        StatusLine status = response.getStatusLine();
        Header[] contentTypeHeaders = response.getHeaders("Content-Type");       
        
        Header contentTypeHeader = contentTypeHeaders[0];        
        //文件类型检测
        boolean foundAllowedContentType = false;
        for(String anAllowedContentType : mAllowedContentTypes) {
            if(Pattern.matches(anAllowedContentType, contentTypeHeader.getValue())) {
                foundAllowedContentType = true;
            }
        }
        
     /*   if(!foundAllowedContentType) {            
            sendFailureMessage(new HttpResponseException(status.getStatusCode(), "Content-Type not allowed!"), 
            		("not image file".getBytes()));
            return;
        }*/
        
		InputStream is = null;
		OutputStream os = null;
        
        try {
            HttpEntity entity = null;
            HttpEntity temp = response.getEntity();
            if(temp != null) {
                entity = new BufferedHttpEntity(temp);
            }
            is = entity.getContent();
            os = new FileOutputStream(file);
			CopyStream(is, os);
			bitmap = decodeFile(file);
         
        } catch(IOException e) {
            sendFailureMessage(e, (byte[]) null);
        }finally{
        	if(os != null){
        		try {
					os.close();
				} catch (IOException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
        	}
        	
        }

        if(bitmap == null) {
            sendFailureMessage(new HttpResponseException(status.getStatusCode(), status.getReasonPhrase()), "download fail ".getBytes());
        } else {
            sendSuccessMessage(status.getStatusCode(), "download success".getBytes());
        }
    }
    
	public static void CopyStream(InputStream is, OutputStream os) {
		final int buffer_size = 1024;
		try {
			byte[] bytes = new byte[buffer_size];
			for (;;) {
				int count = is.read(bytes, 0, buffer_size);
				if (count == -1)
					break;
				os.write(bytes, 0, count);
			}
		} catch (Exception ex) {
		}
	}
	
	private Bitmap decodeFile(File f) {
		InputStream is = null;
		try {
			
			BitmapFactory.Options o = new BitmapFactory.Options();
			o.inJustDecodeBounds = true;
			is = new FileInputStream(f);
			
			BitmapFactory.decodeFile(f.getPath(), o);
			float sw=o.outWidth/MAX_WIDTH;
			float sh=o.outHeight/MAX_WIDTH;
			int scale=1;
			if(sh > 1){
				if(sw>sh){
					scale=(int)sh;
				}else{
					scale=(int)sw;
				}	
			}			
			o.inJustDecodeBounds=false;
			o.inSampleSize = scale;
			
			return BitmapFactory.decodeFile(f.getPath(), o);
		} catch (Exception e) {
			e.printStackTrace();
		}finally{
			try {
				if(is != null){
					is.close();
					is = null;
				}
			} catch (Exception e2) {
				e2.printStackTrace();
			}
		}
		return null;
	}
	
}